import { DownOutlined } from '@ant-design/icons';
import { Button, Col, Form, Input, Row, Select, theme, Divider, Radio, Modal, Table, Space, Tag, Checkbox, Pagination, Switch, message } from 'antd';
import React, { useState, useContext, useEffect } from 'react';
import mycontext from '../../../../utils/myContext';
import http from '../../../../utils/fetchHttp';


const { Option } = Select;// ---表单的内容
let father;
let store//表格编辑对象
let promptBox, promptBoxMethod//提示框
let setListData;//表格数据渲染方法
let queryData;//查询表单数据监听
let queryAllDataList;//查询所有数据
let dataId;//删除数据公用Id

// 搜索表单
const AdvancedSearchForm = () => {
    const { token } = theme.useToken();
    const [form] = Form.useForm();
    const [expand, setExpand] = useState(false);
    const formStyle = {
        maxWidth: 'none',
        background: token.colorFillAlter,
        borderRadius: token.borderRadiusLG,
        padding: 10,
    };
    //点击重置
    const reset = () => {
        queryAllData()
    }

    // 点击筛选后的数据及请求
    const onFinish = (values) => {
        console.log('Received values of form: ', values);
        //查询指定数据
        const getAppointData = (values) => {
            http({
                url: '/promotion/getAppointData',
                method: 'post',
                data: values
            }).then(res => {
                console.log(res);
                if (res.code === 200) {
                    res.data.forEach(item => {
                        item.offsetAmountShow = item.offsetAmount + '元'
                    })
                    setListData(res.data);
                }
            }).catch(() => {
                message.success('请求错误');
            })
        }
        getAppointData(values);
        queryData = getAppointData
    };

    useEffect(() => {
        queryData,
            queryAllDataList,
            queryAllData()
    }, [])

    //查询所有数据
    const queryAllData = () => {
        http({
            url: '/promotion/getAllData',
            method: 'get'
        }).then((res) => {
            if (res.code === 200) {
                res.data.forEach(item => {
                    item.offsetAmountShow = item.offsetAmount + '元'
                })
                setListData(res.data);
            }
        }).catch(() => {
            message.error('请求错误');
        })
    }
    queryAllDataList = queryAllData

    // 添加
    const { getCount } = father;
    const add = () => {
        const value = 1
        getCount(value);
    };
    return (
        <Form form={form} name="advanced_search" style={formStyle} onFinish={onFinish}
            initialValues={{
                promotionTitle: '',
                productGrounding: 0
            }}
        >
            <Row gutter={24}>
                <Col span={8}>
                    <Form.Item
                        name='promotionTitle'
                        label='促销标题'
                        rules={[
                            {
                                message: 'Input something!',
                            },
                        ]}
                    >
                        <Input placeholder="促销标题" />
                    </Form.Item>
                </Col>
                <Col span={8}>
                    <Form.Item
                        name='productGrounding'//初始化动态变得数据
                        label='是否上架'
                    >
                        {/* <Input placeholder="placeholder" /> */}
                        <Select >
                            <Option value={0}>未上架</Option>
                            <Option value={1}>已上架</Option>
                        </Select>
                    </Form.Item>
                </Col>
            </Row>
            {/* 按钮 */}
            <Row>
                <Col
                    span={24}
                    style={{
                        // textAlign: 'right',
                    }}
                >
                    <Button type="primary"
                        style={{
                            margin: '0 0.8rem',
                        }}
                        onClick={() => {
                            add();
                        }}>

                        添加
                    </Button>
                    <Button type="primary" htmlType="submit"
                    >
                        筛选
                    </Button>
                    <Button
                        style={{
                            margin: '0 .8rem',
                        }}
                        onClick={() => {
                            form.resetFields();
                            //发送请求
                            reset();
                        }}
                    >
                        重置
                    </Button>
                </Col>
            </Row>
        </Form>
    );
};
// ----以下是表格
// 表格
const TableDetail = () => {
    const columns = [
        {
            title: '序号',
            dataIndex: 'promotionId',
            key: 'promotionId',
            align: 'center'
        },
        {
            title: '促销标题',
            dataIndex: 'promotionTitle',
            key: 'promotionTitle',
            align: 'center'
        },
        {
            title: '促销详情',
            dataIndex: 'promotionDetail',
            key: 'promotionDetail',
            align: 'center'
        },
        {
            title: '抵用金额',
            dataIndex: 'offsetAmountShow',
            key: 'offsetAmountShow',
            align: 'center'
        },
        {
            title: '使用行程',
            dataIndex: 'promotionType',
            key: 'promotionType',
            align: 'center'
        },
        {
            title: '是否上架',
            dataIndex: 'productGrounding',
            key: 'productGrounding',
            align: 'center',
            render: (_, record) => (
                <Switch
                    checked={record.productGrounding}
                    disabled
                >
                </Switch>
            )
        },
        {
            title: '添加时间',
            dataIndex: 'startTime',
            key: 'startTime',
            align: 'center'
        },
        {
            title: '操作',
            key: 'action',
            align: 'center',
            render: (_, record) => (
                <Space size="middle">
                    <a onClick={() => { gotoCommodityHome(record) }}>商品管理</a>
                    <a onClick={() => { editData(record) }}>编辑</a>
                    <a onClick={() => { delData(record) }}>删除</a>
                </Space>
            ),
        },
    ];
    const [data, setData] = useState([])
    setListData = setData

    //跳转页面
    const { getCount } = father;
    const gotoCommodityHome = (val) => {
        store.promotionProductIdObj = {
            promotionId: val.promotionId
        }
        const value = 2
        getCount(value);
    };
    // 点击编辑
    const editData = (val) => {
        store.promotionHomeEditObj = val
        console.log(val, '222222');
        const value = 4
        getCount(value);
    }
    //点击删除
    const delData = (val) => {
        console.log(val.promotionId, 'val.promotionId');
        dataId = val.promotionId
        promptBoxMethod(true)
    }
    // 选择的数组
    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        },
        getCheckboxProps: (record) => ({
            disabled: record.name === 'Disabled User',
            // Column configuration not to be checked
            name: record.name,
        }),
    };

    return (
        <Table
            rowSelection={{
                type: 'checkbox',
                ...rowSelection,
            }}
            // onRow={(record,index)=>{
            //     console.log(record);
            // }}
            columns={columns}
            dataSource={data}
            pagination={{
                pageSize: 4
            }}
        />
    )
};

const PromotionHome = (props) => {
    store = useContext(mycontext)
    const [isModalOpen, setIsModalOpen] = useState(false);
    promptBox = isModalOpen;
    promptBoxMethod = setIsModalOpen
    const { token } = theme.useToken();
    const listStyle = {
        textAlign: 'center',
        background: token.colorFillAlter,
        borderRadius: token.borderRadiusLG,
        marginTop: 16,
    };
    const handleChange = (value) => {
        console.log(`selected ${value}`);
    };
    const [selectionType, setSelectionType] = useState('checkbox');
    // const [myStatus,setStatus] = useState(dataArr.productGrounding)

    //模态框
    const handleOk = () => {
        const id = {
            id: dataId
        }
        http({
            url: '/promotion/delData',
            method: 'post',
            data: id
        }).then(res => {
            console.log(res);
            if (res.code === 200) {
                message.success('数据删除成功');
                queryAllDataList()
            }
        }).catch(() => {
            message.error('请求错误');

        })
        setIsModalOpen(false);
    };
    const handleCancel = () => {
        message.success('取消删除');
        setIsModalOpen(false);
    };

    //跳转添加促销页面
    father = props

    return (
        <div >
            <AdvancedSearchForm />
            <div style={listStyle}>
                <div style={{ lineHeight: '2rem', display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', height: '2rem', padding: '1rem' }}>
                    <h3>数据列表</h3>
                    <div>
                        <Select
                            defaultValue="批量操作"
                            onChange={handleChange}
                            options={[
                                { value: 'jack', label: '批量删除' },
                                { value: 'lucy', label: '批量XX' },
                            ]}
                        />
                    </div>
                </div>

                <div style={{ lineHeight: '20rem', }}>
                    <Divider />
                    <TableDetail />
                </div>
            </div>
            <Modal
                title="删除确定"
                open={isModalOpen}
                onOk={handleOk}
                onCancel={handleCancel}
                okText={'确定'} cancelText={'取消'}>
                <h3>确定要删除吗？</h3>
            </Modal>
        </div>
    );
}

export default PromotionHome;